//
//  NGLocationViewController.m
//  NetMobileLocation
//
//  Created by Mehmet Sinan Şahin on 3/5/12.
//  Copyright (c) 2012 netgis. All rights reserved.
//

#import "NGLocationViewController.h"
#import "NGLocation.h"
#import "NSDate+Extensions.h"
#import "NGUtility.h"
#import "Status.h"
#import "MapViewController.h"

@interface NGLocationViewController()

-(void) defineLongGesture;

@end


@implementation NGLocationViewController

@synthesize navItem;
@synthesize toLocationsButton;
@synthesize location;
@synthesize lblLat;
@synthesize lblLon;
@synthesize lblDate;
@synthesize lblStatus;
@synthesize btnToMap;
@synthesize imgStatus;
@synthesize lblSpeed;
@synthesize lblTitleSpeed;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{

    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
        nibNameOrNil = [nibNameOrNil stringByAppendingString:@"-ipad"];
    }
        
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        UIButton* backButton = [UIButton buttonWithType:101];
        [backButton setTitle:TTLocalizedString(@"Locations", @"") forState:UIControlStateNormal];        
        [backButton addTarget:self
                       action:@selector(toLocations:)
             forControlEvents:UIControlEventTouchUpInside];
        toLocationsButton = [[UIBarButtonItem alloc] initWithCustomView: backButton];
        
    }
    return self;
}

-(IBAction)toLocations:(id)sender {
    [self.view removeFromSuperview];
}


#pragma mark - touch delegate

-(void) defineLongGesture {
    //create long press gesture recognizer
    UILongPressGestureRecognizer *longPress = 
    [[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)] autorelease];
    [[self view] addGestureRecognizer:longPress];    
}

-(void)longPress:(UILongPressGestureRecognizer*)recognizer {
    if (recognizer.state == UIGestureRecognizerStateEnded) {
        NSString *message = [NSString stringWithFormat:@"%f, %f", location.lat, location.lon];
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        [pasteboard setString:message];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle: TTLocalizedString(@"Copied", @"")
                                                        message: message
                                                       delegate:nil
                                              cancelButtonTitle:TTLocalizedString(@"OK", @"")
                                              otherButtonTitles:nil];
        [alert show];
        [alert release]; 
    }
}

#pragma mark - button actions

-(IBAction)toMap:(id)sender {
    MapViewController *mapCtrl = [[MapViewController alloc] initWithNibName:@"MapViewController" bundle:nil];
    mapCtrl.location = [location retain];
    [self.view addSubview:mapCtrl.view];
    [mapCtrl viewWillAppear:FALSE];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    table.delegate = self;
    table.dataSource = self;
    
    [navItem setLeftBarButtonItem:toLocationsButton animated:FALSE];
    
    /*
    [lblDate setText:[location.tarihSaat toFormattedString]];
    [lblLat setText: [NSString stringWithFormat:@"%f",location.lat]];
    [lblLon setText: [NSString stringWithFormat:@"%f",location.lon]];

    
    if (location.status != HAREKET_EDIYOR && location.status != DURDU) {
        lblTitleSpeed.hidden = YES;
        lblSpeed.hidden = YES;
        btnToMap.hidden = YES;
    } else {
        [lblSpeed setText:[NGUtility friendlySpeed:location]];        
    }
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg.png"]];
    [self defineLongGesture];
    [navItem setTitle:TTLocalizedString(@"Location", @"")];
    
    [titleStatus setText:TTLocalizedString(@"Status", @"")];
    [titleLat setText:TTLocalizedString(@"Latitude", @"")];
    [titleLon setText:TTLocalizedString(@"Longtitude", @"")];
    [lblTitleSpeed setText:TTLocalizedString(@"Speed", @"")];
    */
    
    [imgStatus setImage:[NGUtility imageForNGLocationStatus:location]];
    [lblStatus setText:[NGUtility friendlyStatus:location]];
    [titleStatus setFont:[UIFont boldSystemFontOfSize:16]];
    [titleStatus setText:TTLocalizedString(@"Status", @"")];
    
    if (location.status == UYGULAMA_ACILDI || location.status == UYGULAMA_KAPANDI) {
        [btnToMap setHidden:TRUE];
    } else {
        [btnToMap setHidden:FALSE];
    }
    
}

#pragma mark - table delegates
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = nil;
    if (indexPath.section == 1) {
        cell = statusRow;
        return cell;
    }
    
    NSString *label = @"", *value = @"";
    if (indexPath.section == 0) { //date
        if (indexPath.row == 0) {
            label = TTLocalizedString(@"DateTime", @"DateTime");
            value = [location.tarihSaat toFormattedString];
        }
    } else if (indexPath.section == 2) {
        if (indexPath.row == 0) {
            label = TTLocalizedString(@"Speed", @"Speed");
            value = [NGUtility friendlySpeed:location]; 
        } else if (indexPath.row == 1) {
            label = TTLocalizedString(@"Longtitude", @"Longtitude");
            value = [NSString stringWithFormat:@"%f",location.lon];
        } else if (indexPath.row == 2) {
            label = TTLocalizedString(@"Latitude", @"Latitude");
            value = [NSString stringWithFormat:@"%f",location.lat];
        }
    }
    
    static NSString *cellIdentifier = @"LocationViewCell";
    cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier] autorelease];            
    }
    
    cell.textLabel.text = label;
    cell.detailTextLabel.text = value;
    
    return cell;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        return 1;
    } else if (section == 2) {
        return 3;
    } 
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return @"";
}

/*
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == _DUGME_SECTION) {
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        UIView *backView = [[UIView alloc] initWithFrame:CGRectZero];
        backView.backgroundColor = [UIColor clearColor];
        cell.backgroundView = backView;
        [backView release];     
    }
}
     */

     
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)dealloc {
    [toLocationsButton release];
    [statusRow release];
    [navItem release];
}

@end
